import pymysql
from pymysql.cursors import DictCursor


def main():
    # 创建连接对象
    conn = pymysql.connect(user='root', password='cnp200@HW', database='itcast')
    # 获取游标对象, 设置为字典格式
    curs = conn.cursor(DictCursor)

    try:
        # 新增1条记录
        curs.execute("insert into students(name) values('李磊');")
        # 修改1条记录
        curs.execute("update students set age=29 where name='李磊';")
        # 删除1条记录
        curs.execute("delete from students where name='李磊';")
        # 提交事务
        conn.commit()
    except pymysql.MySQLError:
        # 发生异常回滚
        conn.rollback()

    # pymysql完成数据的查询操作
    curs.execute("select * from students;")
    for record in curs.fetchall():
        print(record)

    # 关闭游标和连接
    curs.close()
    conn.close()


if __name__ == '__main__':
    main()
